水平不高,数据结构小学生,java实现B树,纯原创,为了省事,每一个节点只有key,没有写value属性,周末两天在家全部时间+两个工作日的晚上,兴奋之余发布在csdn上,显摆一下,哈哈
package tree;
public class BTree {
public static final int M = 3;
@SuppressWarnings("unused")
private static final int NODES_MIN_LENGTH = M % 2 == 0 ? M / 2 - 1 : M / 2;
protected BTree parent;
protected int count;
protected Node[] nodes = new Node[M + 1];
public static class Node {
public int key = Integer.MAX_VALUE;
public BTree child;
public Node(int key, BTree child) {
super();
this.key = key;
this.child = child;
}
public Node() {
super();
}
}
public static BTree initBTree() {
BTree btree = new BTree();
for (int i = 0; i < btree.nodes.length; i++) {
btree.nodes[i] = new Node();
}
return btree;
}
public static class Result {
public BTree node;
public boolean find;
public int position;
public Result(BTree node, boolean find, int position) {
super();
this.node = node;
this.find = find;
this.position = position;
}
public Result() {
super();
}
}
public static Result nodeSearch(BTree node, int key) {
Result result = new Result();
result.node = node;
int high = node.count;
int low = 1;
int mid = (low + high) / 2;
while (true) {
if (node.nodes[mid].key == key) {
result.find = true;
result.position = mid;
return result;
}
if (node.nodes[mid].key > key) {
high = mid;
mid = (low + high) / 2;
} else {
low = mid;
mid = (low + high) / 2;
}
if (mid == low) {
if (node.nodes[mid].key == key) {
result.find = true;
result.position = mid;
return result;
}
if (low == high) {
if (node.nodes[mid].key < key) {
result.find = false;
result.position = mid;
return result;
} else {
result.find = false;
result.position = mid - 1;
return result;
}
}
if (node.nodes[mid + 1].key == key) {
result.find = true;
result.position = mid + 1;
return result;
}
if (node.nodes[mid].key < key && node.nodes[mid + 1].key